package pool

import (
	"errors"
	"server/base"
	group2 "server/common/models/group"
	"server/common/models/pool"
	"server/pkg/log"
	"time"
)

var PoolUserLike = poolUserLike{}

type poolUserLike struct{}

func (*poolUserLike) LiveUser(userId int64, likeUserIds []int64, groupId int64) error {
	if likeUserIds == nil || len(likeUserIds) == 0 {
		return errors.New("用户ID不能为空")
	}

	if len(likeUserIds) > 3 {
		return errors.New("最多选择3个哦")
	}

	// 检测自己和用户是否在群组中
	var userCnt int64
	base.Mysql.Model(&group2.GroupUser{}).Where("user_id in ? and group_id = ?", append(likeUserIds, userId), groupId).Count(&userCnt)
	if len(likeUserIds)+1 != int(userCnt) {
		return errors.New("用户不在群组中")
	}

	// 检测是否已经喜欢过
	var likeUsers []pool.PoolUserLike
	base.Mysql.Model(&PoolUserLike).Where("user_id = ?  and group_id = ?", userId, groupId).Count(&likeUsers)
	if len(likeUsers) >= 3 {
		return errors.New("最多选择3个哦")
	}

	for _, v := range likeUserIds {
		// 创建喜欢关系
		data := pool.PoolUserLike{
			UserId:     userId,
			LikeUserId: v,
			GroupId:    groupId,
			Status:     "wait",
			CreateTime: time.Now().Unix(),
			UpdateTime: time.Now().Unix(),
		}
		err := base.Mysql.Create(&data).Error
		if err != nil {
			log.Error("创建喜欢关系失败", err, data)
		}
	}

	return nil
}
